package com.dcsgo.socketPlay.server;

import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

/**
 * @author DCSGO
 * @version 1.0
 * 监听客户端连接
 */
public class Server {
    private static final Properties serverProperties = new Properties();
    private static final Properties gameProperties = new Properties();

    static {
        System.out.println("正在读取配置信息...");
        try {
            serverProperties.load(new FileReader("./serverProperties.properties"));
            gameProperties.load(new FileReader("./game.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getServerProperty(String key) {
        return serverProperties.getProperty(key);
    }

    public static Properties getGameProperties() {
        return gameProperties;
    }

    public Server() throws IOException {
        String serverPort = serverProperties.getProperty("serverPort");
        System.out.println("配置信息读取完成!");
        int port = Integer.parseInt(serverPort);
        ServerSocket serverSocket = new ServerSocket(port);
        Integer clientId = 0;
        while (true) {
            System.out.println("等待用户连接...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("有用户连接! 分配的id = " + clientId);
            //启动服务线程
            ServeClientsThread serveClientsThread = new ServeClientsThread(clientId, clientSocket);
            serveClientsThread.start();
            System.out.println("已启动服务线程!");
            ServeClientsThreadManager.put(clientId, serveClientsThread);
            System.out.println("已将该服务线程存入threads!");
            //将该clientSocket 添加至ClientSocketManager
            ClientSocketManager.put(clientId, clientSocket);
            System.out.println("已将该连接存入clients!");
            clientId++;

        }
    }
}
